/**
 * Created by Dell on 2017/5/8.
 */
'use strict';
let pg = require ('../lib/pgClient');
let log = require ('log4js').getLogger('models/systemlogs');
/**
 * 添加日志
 * @param params
 * @param callback
 */
const add_sql = ' INSERT INTO systemlogs (adminid,"desc", createtime, type) VALUES ($1, $2, $3, $4)';//添加日志
exports.add_systemlogs = function(params, callback){
    pg.query(add_sql, params, function(err, result){//执行添加操作
        if(err){
            callback (err, null);
        }else{
            callback (err, result);//添加日志
        }
    });
};
/**
 * 后台多条件查询日志列表
 * @param params
 * @param args
 * @param callback
 */
exports.list = function(params, args, callback){
    let sql = 'SELECT s.*, a.adminname, a.mobile FROM systemlogs s,admin a WHERE a.id = s.adminid';
    let number = 1;
    if(args.keyword){
        sql += ' AND (s."desc" like $'+number+' OR a.adminname like $'+number+' OR a.mobile like $'+number+')';
        number ++;
    }
    sql += ' ORDER BY s.createtime DESC LIMIT $'+number+' OFFSET $'+(number+1);
    pg.query(sql, params, function(err, result){//直行sql语句
        if(err){
            callback (err, null);//执行查询操作报错
        }else {
            callback (err, result);//返回结果
        }
    })
};
/**
 * 后台多条件查询日志列表数据统计
 * @param params
 * @param args
 * @param callback
 */
exports.count = function(params, args, callback){
    let sql = 'SELECT count(*) FROM systemlogs s, admin a WHERE a.id = s.adminid';
    let number = 1;
    if(args.keyword){
        sql += ' AND (s."desc" like $'+number+' OR a.adminname like $'+number+' OR a.mobile like $'+number+')';
        number ++;
    }
    pg.query(sql, params, function(err, result){//直行sql语句
        if(err){
            callback (err, null);//执行查询操作报错
        }else {
            callback (err, result);//返回结果
        }
    });
};
/**
 * 后台批量删除日志
 * @param args
 * @param callback
 */
exports.remove = function(args, callback){
    let ids = args.ids;//ids 是数组
    let theids = "'"+ids.join("','")+"'";//将数组ids整理成字符串
    const sql1 = 'SELECT * FROM systemlogs WHERE id in ('+theids+')';//是否有日志
    const sql2 = 'DELETE FROM systemlogs WHERE id in ('+theids+')';//删除日志
    pg.query(sql1, [], function(err, result){//执行sql语句
        if(err){
            callback (err, null);//查找报错
        }else if (result.rowCount == 0){
            callback (err, 'null');//没有日志记录
        }else{
            pg.query(sql2, [], function(err, result){//执行删除操作
                if(err){
                    callback (err, null);
                }else if(result.rowCount == 0){
                    callback (err, 'fail');//报错
                }else {
                    callback (err, result);
                }
            })
        }
    })
};